package com.ht.web_vr_home_tour_backend.dao;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.*;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ht.web_vr_home_tour_backend.utils.exceptions.MessageException;
import com.ht.web_vr_home_tour_backend.utils.exceptions.OssException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

@Component
@Data
@ConfigurationProperties(prefix = "custom.oss")
public class OssImpl implements Oss {
    private String ossUrl; // 通过 yaml 配置

    @PostConstruct
    public void init() {
        System.out.println("ossUrl: " + ossUrl);
    }

    @Override
    public String upload(InputStream is) {
        HttpRequest post = HttpUtil.createPost( ossUrl + "api/img/");
        post.contentType(ContentType.MULTIPART.getValue());
        FastByteArrayOutputStream os = IoUtil.read(is);
        byte[] data = os.toByteArray();
        post.form("file", data, "file");
        try (
                HttpResponse response = post.execute();
        ) {
            JSON parse = JSONUtil.parse(response.body());
            Object success = parse.getByPath("success");
            if (success instanceof Boolean) {
                if ((Boolean) success) {
                    return parse.getByPath("data").toString();
                }
            }
            throw new Exception();
        } catch (Exception e) {
            throw new OssException();
        }
    }

    @Override
    public InputStream download(String md5) {
        HttpRequest get = HttpUtil.createGet(this.ossUrl + "api/img/" + md5);
        try (
                HttpResponse response = get.execute();
                InputStream is = response.bodyStream()
        ) {
            return is;
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    @Override
    public void delete(String md5) {
        if (md5 == null) {
            return;
        }
        HttpRequest get = HttpUtil.createGet(this.ossUrl + "api/img/" + md5);
        get.method(Method.DELETE);
        try (
                HttpResponse response = get.execute()
        ) {
            JSON json = JSONUtil.parse(response.body());
            if (!(Boolean) json.getByPath("success")) {
                throw new MessageException("删除失败，请稍后重试");
            }
        }
    }
}


